import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'server_config.dart';

/// 本地配置管理器 - 简化版本，直接操作本地存储
class LocalConfigManager {
  static const String _configKey = 'app_config';
  static LocalConfigManager? _instance;
  SharedPreferences? _prefs;
  Map<String, dynamic> _configCache = {};
  
  // 配置变更通知
  final List<VoidCallback> _listeners = [];

  LocalConfigManager._();

  static LocalConfigManager get instance {
    _instance ??= LocalConfigManager._();
    return _instance!;
  }

  /// 初始化
  Future<void> initialize() async {
    _prefs = await SharedPreferences.getInstance();
    await _loadFromLocal();
    debugPrint('📋 LocalConfigManager: 初始化完成');
  }

  /// 从本地存储加载配置
  Future<void> _loadFromLocal() async {
    try {
      final configJson = _prefs?.getString(_configKey);
      if (configJson != null && configJson.isNotEmpty) {
        _configCache = json.decode(configJson) as Map<String, dynamic>;
        debugPrint('📥 LocalConfigManager: 从本地加载配置成功，配置项: ${_configCache.keys.length}个');
        
        // 打印关键配置项用于调试
        final baseUrl = _configCache['baseUrl'] ?? 'not set';
        final tcpHost = _configCache['tcpHost'] ?? 'not set';
        final tcpPort = _configCache['tcpPort'] ?? 'not set';
        debugPrint('🔧 当前配置: baseUrl=$baseUrl, tcpHost=$tcpHost, tcpPort=$tcpPort');
        
        // 🔥 检测并更新开发环境配置为生产环境配置
        final needsUpdate = _shouldUpdateToServerConfig();
        if (needsUpdate) {
          debugPrint('⚠️ 检测到开发环境配置(127.0.0.1/localhost)，自动更新为 ServerConfig 配置');
          await _setDefaultConfig();
        }
      } else {
        // 如果没有本地配置，使用默认配置
        await _setDefaultConfig();
        debugPrint('🔧 LocalConfigManager: 使用默认配置');
      }
    } catch (e) {
      debugPrint('❌ LocalConfigManager: 加载本地配置失败: $e');
      await _setDefaultConfig();
    }
  }
  
  /// 检查是否需要更新为 ServerConfig 的配置
  /// 如果当前持久化配置是开发环境地址，但 ServerConfig 是生产环境地址，则需要更新
  bool _shouldUpdateToServerConfig() {
    final currentBaseUrl = _configCache['baseUrl'] as String? ?? '';
    final currentTcpHost = _configCache['tcpHost'] as String? ?? '';
    
    // 检查当前配置是否是开发环境地址
    final isCurrentDev = _isDevAddress(currentBaseUrl) || _isDevAddress(currentTcpHost);
    
    // 检查 ServerConfig 是否是生产环境地址
    final isServerConfigProd = !_isDevAddress(ServerConfig.baseUrl) && !_isDevAddress(ServerConfig.tcpHost);
    
    // 如果当前是开发环境，但 ServerConfig 是生产环境，则需要更新
    if (isCurrentDev && isServerConfigProd) {
      return true;
    }
    
    // 如果 ServerConfig 的地址与当前配置完全不同，也需要更新
    if (currentBaseUrl.isNotEmpty && 
        !currentBaseUrl.contains(ServerConfig.baseUrl.replaceAll('http://', '').replaceAll('https://', '').split(':')[0])) {
      debugPrint('🔄 ServerConfig 地址已更改，需要更新本地配置');
      return true;
    }
    
    return false;
  }
  
  /// 判断是否是开发环境地址
  bool _isDevAddress(String address) {
    return address.contains('127.0.0.1') ||
           address.contains('localhost') ||
           address.contains('192.168.') ||
           address.contains('10.0.');
  }

  /// 设置默认配置
  /// 从 ServerConfig 类加载编译时配置
  Future<void> _setDefaultConfig() async {
    debugPrint('📋 LocalConfigManager: 使用 ServerConfig 中的默认配置');
    
    // 直接从 ServerConfig 获取配置
    _configCache = ServerConfig.toMap();
    
    debugPrint('✅ 默认配置加载成功:');
    debugPrint('   baseUrl: ${_configCache['baseUrl']}');
    debugPrint('   tcpHost: ${_configCache['tcpHost']}');
    debugPrint('   tcpPort: ${_configCache['tcpPort']}');
    
    await _saveToLocal();
  }

  /// 保存配置到本地存储
  Future<bool> _saveToLocal() async {
    try {
      final configJson = json.encode(_configCache);
      final success = await _prefs?.setString(_configKey, configJson) ?? false;
      if (success) {
        debugPrint('💾 LocalConfigManager: 配置保存成功');
        _notifyListeners();
      } else {
        debugPrint('❌ LocalConfigManager: 配置保存失败');
      }
      return success;
    } catch (e) {
      debugPrint('❌ LocalConfigManager: 保存配置异常: $e');
      return false;
    }
  }

  /// 获取配置值
  T? getValue<T>(String key, [T? defaultValue]) {
    final value = _configCache[key];
    if (value is T) {
      return value;
    }
    return defaultValue;
  }

  /// 强制重新加载配置从SharedPreferences
  Future<void> forceReload() async {
    debugPrint('🔄 LocalConfigManager: 强制重新加载配置');
    try {
      final configJson = _prefs?.getString(_configKey);
      if (configJson != null && configJson.isNotEmpty) {
        final newConfig = json.decode(configJson) as Map<String, dynamic>;
        _configCache = newConfig;
        debugPrint('✅ LocalConfigManager: 强制重新加载完成，配置项: ${_configCache.keys.length}个');
        
        // 打印关键配置项用于调试
        final baseUrl = _configCache['baseUrl'] ?? 'not set';
        final tcpHost = _configCache['tcpHost'] ?? 'not set';
        final tcpPort = _configCache['tcpPort'] ?? 'not set';
        debugPrint('🔧 重新加载后配置: baseUrl=$baseUrl, tcpHost=$tcpHost, tcpPort=$tcpPort');
        
        _notifyListeners();
      } else {
        debugPrint('⚠️ LocalConfigManager: SharedPreferences中无配置，使用默认配置');
        await _setDefaultConfig();
      }
    } catch (e) {
      debugPrint('❌ LocalConfigManager: 强制重新加载失败: $e');
    }
  }

  /// 设置配置值
  Future<bool> setValue<T>(String key, T value) async {
    final oldValue = _configCache[key];
    _configCache[key] = value;
    
    debugPrint('🔧 LocalConfigManager: 设置配置 $key: $oldValue → $value');
    return await _saveToLocal();
  }

  /// 批量设置配置值
  Future<bool> setValues(Map<String, dynamic> values) async {
    debugPrint('🔧 LocalConfigManager: 批量设置配置，共 ${values.length} 项');
    
    bool hasChanges = false;
    for (final entry in values.entries) {
      final oldValue = _configCache[entry.key];
      if (oldValue != entry.value) {
        _configCache[entry.key] = entry.value;
        hasChanges = true;
        debugPrint('   └─ ${entry.key}: $oldValue → ${entry.value}');
      }
    }
    
    if (hasChanges) {
      return await _saveToLocal();
    } else {
      debugPrint('📋 LocalConfigManager: 没有配置变更');
      return true;
    }
  }

  /// 获取所有配置
  Map<String, dynamic> getAllConfig() {
    return Map<String, dynamic>.from(_configCache);
  }

  /// 清除所有配置
  Future<bool> clearAll() async {
    debugPrint('🧹 LocalConfigManager: 清除所有配置');
    _configCache.clear();
    final success = await _prefs?.remove(_configKey) ?? false;
    if (success) {
      await _setDefaultConfig();
    }
    return success;
  }

  /// 重置为默认配置
  Future<bool> resetToDefault() async {
    debugPrint('🔄 LocalConfigManager: 重置为默认配置');
    await _setDefaultConfig();
    return true;
  }

  /// 添加配置变更监听器
  void addListener(VoidCallback listener) {
    _listeners.add(listener);
    debugPrint('📋 LocalConfigManager: 添加监听器，当前总数: ${_listeners.length}');
  }

  /// 移除配置变更监听器
  void removeListener(VoidCallback listener) {
    _listeners.remove(listener);
    debugPrint('📋 LocalConfigManager: 移除监听器，当前总数: ${_listeners.length}');
  }

  /// 通知所有监听器
  void _notifyListeners() {
    debugPrint('📢 LocalConfigManager: 通知 ${_listeners.length} 个监听器配置已变更');
    for (final listener in _listeners) {
      try {
        listener();
      } catch (e) {
        debugPrint('❌ LocalConfigManager: 监听器通知失败: $e');
      }
    }
  }

  /// 强制刷新配置（重新从本地加载）
  Future<void> refresh() async {
    debugPrint('🔄 LocalConfigManager: 强制刷新配置');
    await _loadFromLocal();
  }

  /// 导出配置（用于备份）
  String exportConfig() {
    return json.encode(_configCache);
  }

  /// 导入配置（用于恢复）
  Future<bool> importConfig(String configJson) async {
    try {
      final config = json.decode(configJson) as Map<String, dynamic>;
      debugPrint('📥 LocalConfigManager: 导入配置，共 ${config.length} 项');
      
      _configCache = config;
      return await _saveToLocal();
    } catch (e) {
      debugPrint('❌ LocalConfigManager: 导入配置失败: $e');
      return false;
    }
  }

  /// 获取配置的调试信息
  String getDebugInfo() {
    final info = StringBuffer();
    info.writeln('=== LocalConfigManager 调试信息 ===');
    info.writeln('配置项总数: ${_configCache.length}');
    info.writeln('监听器数量: ${_listeners.length}');
    info.writeln('配置详情:');
    
    _configCache.forEach((key, value) {
      info.writeln('  $key: $value (${value.runtimeType})');
    });
    
    return info.toString();
  }

  /// 清理资源
  void dispose() {
    _listeners.clear();
    debugPrint('🧹 LocalConfigManager: 已清理');
  }
}

/// 配置变更Mixin - 简化版本
mixin LocalConfigAwareMixin<T extends StatefulWidget> on State<T> {
  VoidCallback? _configListener;

  @override
  void initState() {
    super.initState();
    _configListener = () {
      if (mounted) {
        onConfigurationChanged();
      }
    };
    LocalConfigManager.instance.addListener(_configListener!);
  }

  @override
  void dispose() {
    if (_configListener != null) {
      LocalConfigManager.instance.removeListener(_configListener!);
    }
    super.dispose();
  }

  /// 配置变更回调 - 子类需要重写此方法
  void onConfigurationChanged() {
    // 默认刷新UI
    if (mounted) {
      setState(() {});
    }
  }
}
